<template>
    <div>
      <div class="row gutter-lg" style="height:100%;">
        <div class="col-12" style="min-height:220px;border-right:1px solid #ccc;">
          <template>
            <div class="q-py-sm">
              <q-btn  size="sm" color="light-blue" :label="$t('分配')" @click="addOrEditDialog=true"/>
            </div>
          </template>
          <hr>
          <q-splitter
            v-model="splitterModel"
          >
            <template v-slot:before style="width:10%;">
              <q-tabs
                v-for="(data,index) in classificationdata"
                :key="index"
                v-model="tab"
                vertical
                inline-label
                dense
                class="text-teal"
              >
               <q-popup-proxy context-menu>
                  <q-list dense class="text-grey">
                    <q-item clickable v-close-popup  v-if="data.status==1" @click="updateStatus(data,status=-1)">
                      <q-item-section>
                        <q-item-label>失效</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup  v-if="data.status==-1" @click="updateStatus(data,status=1)">
                      <q-item-section>
                        <q-item-label>启用</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup  v-if="data.status==-1" @click="delectCompany(data)">
                      <q-item-section>
                        <q-item-label>删除</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
               </q-popup-proxy>
                <q-tab  :name="data.id" :label="data.name">
                  <q-badge class="q-ml-sm" transparent align="middle" color="positive"  v-if="data.status==1">
                    启用
                  </q-badge>
                  <q-badge class="q-ml-sm" transparent align="middle" color="grey"  v-if="data.status==-1">
                    失效
                  </q-badge>
                  <!-- <q-chip dense square label="启用" color="positive" text-color="white"/> -->
                  <!-- <q-chip dense square label="失效" color="grey" text-color="white" v-if="data.type==2"/> -->
                </q-tab>
              </q-tabs>
            </template>
            <template v-slot:after>
              <template>
                <div class="q-py-sm" style="padding:10px;">
                  <q-btn  size="sm" color="light-blue" :loading="loadingSave" :label="$t('保存')" @click="saveCommany"/>
                </div>
              </template>
              <q-card>
                <q-card-section>
                  <div class="row q-col-gutter-sm">
                    <div class="col-3">
                      <div :class="$v.addOrEditForm.currentcyCode.$error?'text-negative': ''">订单货币</div>
                     <q-select
                      emit-value
                      map-options
                      dense
                      :error="$v.addOrEditForm.currentcyCode.$error"
                      @blur="$v.addOrEditForm.currentcyCode.$touch"
                      v-model="addOrEditForm.currentcyCode"
                      :options="moneyConOption" />
                    </div>
                    <div class="col-3">
                      <div :class="$v.addOrEditForm.paymentTermCode.$error?'text-negative': ''">付款条件</div>
                      <q-select
                      emit-value
                      map-options
                      dense
                      :error="$v.addOrEditForm.paymentTermCode.$error"
                      @blur="$v.addOrEditForm.paymentTermCode.$touch"
                      v-model="addOrEditForm.paymentTermCode"
                      :options="payConOption" />
                    </div>
                  </div>
                </q-card-section>
              </q-card>
            </template>
          </q-splitter>
        </div>
      </div>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '分配公司':'分配公司'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:30vh;max-height:60vh'" class="scroll">
          <q-table
            flat
            dense
            class="bg-white"
            :data="dataDep"
            :columns="columnsDep"
            row-key="id"
            separator="cell"
            selection="multiple"
            :selected.sync="selectedDep"
            :visible-columns="visibleColumnsDep"
            :pagination.sync="paginationDep"
            :rows-per-page-options="[10, 20, 30, 40]"
            :filter="searchFormDep"
            no-data-label="暂无数据"
            table-class="h-custom"
            @request="getSeleetTable"
          >
            <template v-slot:top-right="props">
              <q-select
                v-model="visibleColumnsDep"
                multiple
                borderless
                options-dense
                :display-value="$t('显示列')"
                emit-value
                map-options
                :options="columnsDep"
                option-value="name"
                class="q-mx-lg"
              >
                <template v-slot:option="scope">
                  <q-item
                    v-bind="scope.itemProps"
                    v-on="scope.itemEvents"
                    v-if="!scope.opt.required"
                  >
                    <q-item-section avatar>
                      <q-toggle color="blue" v-model="visibleColumnsDep" :val="scope.opt.name" />
                    </q-item-section>
                    <q-item-section style="min-width:60px">
                      {{ scope.opt.label }}
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
              <q-toggle
                v-model="searchToggleDep"
                left-label
                label="搜索"
                color="blue"
                checked-icon="check"
                unchecked-icon="clear"
                keep-color
              />
              <q-btn
                flat round dense
                :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
                @click="props.toggleFullscreen"
                class="q-ml-md"
              />
            </template>
            <template v-if="searchToggleDep" v-slot:top-row="props">
              <q-tr :props="props">
                <q-td>
                  <q-btn color="primary" dense flat icon="search" @click="getSeleetTable({ pagination: paginationDep, filter: searchFormDep })"/>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
                  <!-- <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchFormGroup })"/> -->
                  <q-input dense outlined v-model="searchFormDep[col.name]"/>
                </q-td>
              </q-tr>
            </template>
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th>
                  <q-checkbox indeterminate-value="some" dense v-model="props.selected"/>
                </q-th>
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  {{ col.label }}
                </q-th>
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td width="52">
                  <q-checkbox dense v-model="props.selected" :disable="tabId.indexOf(props.row.id)==-1?false : true"/>
                </q-td>
                <q-td key="action" :props="props">
                  <q-btn-dropdown
                    color="blue"
                    size="sm"
                    dense
                    menu-anchor="bottom left"
                    menu-self="top left"
                    content-class="text-grey"
                    icon="settings">
                    <q-list dense>
                      <q-item clickable v-close-popup @click="delGroupRowDep(props.row)">
                        <q-item-section>
                          <q-item-label>删除</q-item-label>
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </q-btn-dropdown>
                </q-td>
                <q-td key="code" :props="props">{{ props.row.code  }}</q-td>
                <q-td key="name" :props="props">{{ props.row.name }}</q-td>
                <q-td key="nameEn" :props="props">{{ props.row.nameEn }}</q-td>
                <q-td key="createUserName" :props="props">{{ props.row.createUserName }}</q-td>
                <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
              </q-tr>
              <q-tr v-show="props.expand" :props="props">
                <q-td colspan="100%">
                </q-td>
              </q-tr>
            </template>
            <template v-slot:pagination="props">
              <q-pagination
                v-model="paginationDep.page"
                color="blue"
                :max-pages="5"
                :max="pages"
                :boundaryLinks="true"
                :directionLinks="true"
              />
              共 {{ totalDep }} 条
            </template>
          </q-table>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="saveSuOrgamzation"/>
        </q-card-actions>
      </q-card>
    </q-dialog>
    </div>
</template>

<script>
// import _ from 'lodash'
import { required } from 'vuelidate/lib/validators'
// import { transformToTreeFormat } from 'src/utils/fns'
import Dict from 'src/utils/dictionaries'
export default {
  props: {
    id: {
    }
  },
  data () {
    return {
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 公司科目
      moneyConOption: [],
      payConOption: [],
      classificationdata: [],
      splitterModel: 20,
      tab: '',
      tabId: [],
      // 品类tab
      caTab: 'tab1',
      filter: '',
      data: [],
      ticked: [],
      tickStrategy: 'strict',
      selected: '',
      nodeExpand: [],
      nodeSelected: '',
      addOrEdit: 1,
      parentId: '0',
      ischeck: 2,
      maximizedToggle: false,
      loadingSave: false,
      addOrEditDialog: false,
      visibleColumnsDep: [
        'code',
        'name',
        'nameEn',
        'createUserName',
        'createTime'
      ],
      searchFormDep: {
        code: '',
        name: '',
        nameEn: '',
        createUserName: '',
        createTime: ''
      },
      totalDep: 0,
      paginationDep: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      selectedDep: [],
      dataDep: [],
      datas: [],
      classification: {},
      searchToggleDep: false,
      tickable: true,
      addOrEditForm: {
        currentcyCode: '',
        currentcyName: '',
        // currentcyId: '',
        paymentTermName: '',
        paymentTermCode: ''
        // paymentTermId: ''
      },
      columnsDep: [
        { name: 'code', required: true, label: '编码', align: 'left', field: 'code', sortable: true },
        { name: 'name', required: true, label: '名称', align: 'left', field: 'name', sortable: true },
        { name: 'nameEn', required: true, label: '英文名称', align: 'left', field: 'nameEn', sortable: true },
        { name: 'createUserName', field: 'createUserName', align: 'left', label: '创建人', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ]
    }
  },
  validations: {
    addOrEditForm: {
      paymentTermCode: { required },
      currentcyCode: { required }
    }
  },
  created () {
    this.getleft()
    this.getAccount()
    this.getpayCon()
    this.getpayWay()
  },
  computed: {
    pages () {
      return Math.ceil(this.totalDep / this.paginationDep.rowsPerPage)
    }
  },
  watch: {
    'paginationDep.page' () {
      this.getSeleetTable({
        pagination: this.paginationDep,
        filter: this.searchFormDep
      })
    },
    'addOrEditDialog' () {
      if (this.addOrEditDialog === true) {
        this.getSeleetTable({
          pagination: this.paginationDep,
          filter: this.searchFormDep
        })
      }
    },
    'tab' () {
      this.$v.addOrEditForm.$reset()
      this.getImage()
    }
  },
  methods: {
    // 查询信息
    async getImage () {
      await this.$api({
        method: 'get',
        url: `/mdm/supplierBuyerOrg/findById/${this.tab}`,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.addOrEditForm = { ...data }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.addOrEdit = 2
      this.addOrEditTab = 'tab1'
      this.$v.addOrEditForm.$reset()
    },
    // 保存信息
    async saveCommany () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        console.log(this.accountOption)
        this.loadingSave = true
        this.payConOption.forEach(item => {
          if (this.addOrEditForm.paymentTermCode === item.value) {
            // this.addOrEditForm.payConCode = item.code
            this.addOrEditForm.paymentTermName = item.label
          }
        })
        this.moneyConOption.forEach(item => {
          if (this.addOrEditForm.currentcyCode === item.value) {
            this.addOrEditForm.currentcyName = item.label
          }
        })
        // this.addOrEditForm.purOrgId = this.tab
        this.addOrEditForm.supplierMainId = this.id
        console.log(this.addOrEditForm)
        await this.$api({
          method: 'put',
          url: '/mdm/supplierBuyerOrg/update',
          params: this.addOrEditForm,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
      }
    },
    // 获取货币
    async getAccount () {
      await this.$api({
        method: 'post',
        url: `/common/currency/selectAll`,
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(data)
          let arr = []
          data.forEach(item => {
            let o = {}
            o.label = item.name
            // o.code = item.code
            o.value = item.code
            arr.push(o)
          })
          this.moneyConOption = arr
        }
      })
    },
    async getpayCon () {
      await this.$api({
        method: 'post',
        url: `/common/dict/findByTypeCode/${Dict.DictionariesType.PAY_CONDITION}`,
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(data)
          let arr = []
          data.forEach(item => {
            let o = {}
            o.label = item.name
            o.value = item.code
            // o.code = item.code
            arr.push(o)
          })
          this.payConOption = arr
        }
      })
    },
    async getpayWay () {
      await this.$api({
        method: 'post',
        url: `/common/dict/findByTypeCode/${Dict.DictionariesType.PAY_METHOD}`,
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(data)
          let arr = []
          data.forEach(item => {
            let o = {}
            o.label = item.name
            o.code = item.code
            o.value = item.id
            arr.push(o)
          })
          this.payWayOption = arr
        }
      })
    },
    delectCompany (data) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除组织：${data.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/supplierBuyerOrg/delete/${data.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.getleft()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }).onCancel(() => {

      })
    },
    // 修改状态
    updateStatus (data, status) {
      let name = ''
      if (status === -1) {
        name = '失效'
      } else {
        name = '启用'
      }
      this.$q.dialog({
        title: '删除',
        message: `确认要${name}组织：${data.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'put',
          url: `/mdm/supplierBuyerOrg/update`,
          params: {
            id: data.id,
            status: status
          },
          emulateJSON: true,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.getleft()
      }).onCancel(() => {

      })
    },
    async saveSuOrgamzation () {
      if (this.selectedDep.length !== 0) {
        let company = []
        this.selectedDep.forEach(item => {
          if (this.tabId.length === 0) {
            company.push(item.id)
          } else if (this.tabId.indexOf(item.id) === -1) {
            company.push(item.id)
          }
        })
        await this.$api({
          method: 'put',
          url: '/mdm/supplierBuyerOrg/addList',
          params: {
            ids: company.join(','),
            supplierMainId: this.id
          },
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditDialog = false
            this.getleft()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      } else {
        this.$q.notify({
          message: '请选择分配的公司',
          color: 'negative',
          icon: 'error_outline',
          position: 'top-right',
          timeout: 3000
        })
      }
    },
    async getSeleetTable (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/mdm/businessOrg/query',
        params: {
          pageNo: page,
          typeCode: '0002',
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(this.tabId)
          this.tabId.forEach(item => {
            for (let i in data.list) {
              if (data.list[i].id === item) {
                this.selectedDep.push(data.list[i])
              }
            }
          })
          this.totalDep = data.total
          this.dataDep = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.paginationDep.page = page
      this.paginationDep.rowsPerPage = rowsPerPage
      this.paginationDep.sortBy = sortBy
      this.paginationDep.descending = descending
    },
    async add () {
      if (this.datas.length === 0 && this.ticked.length === 0) {
        this.$q.notify({
          message: '请选择品类',
          color: 'negative',
          icon: 'error_outline',
          position: 'top-right',
          timeout: 3000
        })
      } else {
        console.log(this.classification)
        this.classification = {}
        this.classification.categroyTypeId = this.tab
        this.classification.categoryIds = this.ticked
        if (JSON.stringify(this.classification) === '{}') {
        } else {
          if (this.datas.length === 0) {
            console.log(this.classification)
            if (this.classification.length !== 0) {
              this.datas.push(this.classification)
            }
          } else {
            this.getNew(this.datas)
          }
        }
        if (this.datas.length === 0) {
          this.$q.notify({
            message: '请选择品类',
            color: 'negative',
            icon: 'error_outline',
            position: 'top-right',
            timeout: 3000
          })
        } else {
          console.log(this.datas)
          await this.$api({
            method: 'put',
            url: `/mdm/item/category/save`,
            params: {
              categoryTypeCateRels: this.datas,
              itemSiteId: this.selectSiteId
            },
            emulateJSON: true,
            useLoadLayer: true,
            successCallback: ({ data }) => {
              // this.tickStrategy = 'leaf'
              this.tickable = false
              this.ischeck = 2
              this.getTree()
              this.getSeleetTable()
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          })
        }
      }
    },
    async getleft () {
      await this.$api({
        method: 'post',
        url: `/mdm/supplierBuyerOrg/queryNoPageBusinesOrgDTO`,
        params: {
          supplierMainId: this.id
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.tabId = []
          data.forEach(item => {
            this.tabId.push(item.businesOrgId)
          })
          this.classificationdata = data
          this.tab = data[0].id
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
  /deep/.q-item
    min-height 30px
    max-height 35px
  /deep/ .q-splitter__before
    width 10% !important
    margin-left 20px
    min-height 200px
  /deep/ .q-splitter__after
    width 90% !important
  /deep/ .text-center
    text-align left !important
  .q-checkbox__check-indet
    width: 100%;
    height: 0;
    left: 0;
    top: 50%;
    border-color: #fff;
    border-width: 1px;
    border-style: solid;
</style>
